import koa from "koa";
import koa_router from "koa-router";
import koa_cors from "koa2-cors";
import koa_session from "koa-session";
import Fn from "../../common/Fn";

let t = "[LWeb]"

export type koaCtx = koa.ParameterizedContext<any, koa_router.IRouterParamContext<any, {}>, any>

export default class LWeb {
    private httpServer: koa;
    private router: koa_router;

    constructor(port: number) {
        this.httpServer = new koa();
        this.router = new koa_router();
        this.httpServer.use(koa_cors());
        this.httpServer.use(this.router.routes());

        const CONFIG = {
            key: 'koa:sess',   //cookie key (default is koa:sess)
            maxAge: 86400000,  // cookie的过期时间 maxAge in ms (default is 1 days)
            overwrite: true,  //是否可以overwrite    (默认default true)
            httpOnly: true, //cookie是否只有服务器端可以访问 httpOnly or not (default true)
            signed: true,   //签名默认true
            rolling: false,  //在每次请求时强行设置cookie，这将重置cookie过期时间（默认：false）
            renew: false,  //(boolean) renew session when session is nearly expired,
        };
        this.httpServer.use(koa_session(CONFIG, this.httpServer));

        this.httpServer.listen(port);
    }

    on(key: string, func: (data: any, c: koaCtx) => Promise<any>) {
        this.router.get('/' + key, async (ctx, next) => {
            ctx.type = 'json';

            let data = ctx.query;
            let res = await func(data, ctx);
            if (typeof res == "object") {
                ctx.body = JSON.stringify(res);
            } else {
                ctx.body = res;
            }
        });
    }

    private getPostData(ctx: koaCtx) {
        return new Promise<string>((resolve, reject) => {
            try {
                let params = '';
                ctx.req.on('data', (chunk: any) => {
                    params += chunk;
                })
                ctx.req.on('end', (chunk: any) => {
                    resolve(params)
                })
            } catch (error) {
                console.log("获取post提交的数据错误")
                reject(error)
            }
        })
    }

    post(key: string, func: (data: any, c: koaCtx) => Promise<any>) {
        this.router.post('/' + key, async (ctx: koaCtx, next: any) => {
            let data = await this.getPostData(ctx);
            data = Fn.safeJson(data);
            ctx.type = 'json';
            let res = await func(data, ctx);
            if (typeof res == "object") {
                ctx.body = JSON.stringify(res);
            } else {
                ctx.body = res;
            }
        });
    }
}